<?php

namespace App\Console\Commands;

use App\Models\Asset;
use App\Services\WalletService;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Predis\Client;

class AssetSyncCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'asset:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '通过asset表同步发行平台证书编号';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $client = new Client();

        $ids = $client->get('asset_ids');
        // 查询已同步的资产ID列表
        $assets = Asset::where('cert_sn', '')->when($ids, function ($q) use ($ids) {
            return $q->whereNotIn('id', json_decode($ids, true));
        })->where('trans_hash', '!=', '')->limit(20)->get();

        $air_ids = array_column(json_decode(json_encode($assets), true), 'id');

        $client->set('asset_ids', json_encode($air_ids));

        $walletService = new WalletService();

        foreach ($assets as $asset) {
            try {
                $transEvidence = $walletService->tokenTransEvidence($asset->token_id, $asset->trans_hash);

                $asset->cert_sn = Arr::get($transEvidence, 'certSN');

                $asset->save();
            } catch (\Exception $e) {
                Log::error($e->getMessage());

                continue;
            }
        }

        return Command::SUCCESS;
    }
}
